package com.easyj.base.security.service;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import com.easyj.base.security.SimpleUser;

import java.io.Serializable;
import java.util.Collection;


/**
 * 权限处理,
 * 自动注入 org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
 */
@Component
public class DefaultPermissionEvaluator implements PermissionEvaluator {
	/**
	 * targetDomainObject:功能模块名称，（暂不作校验）
	 * targetPermission：具体权限代码，用户必须有此权限代码  ，多个权限用','隔开，表示只要有其中一个就可
	 *   例如：
	 * @PreAuthorize("hasPermission('user','user:edit')")
	 * @PreAuthorize("hasPermission('user','user:list,user:edit')") 用户查看或编辑权取
	 */
	@Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object targetPermission) {
        // 获得权限
        SimpleUser user = (SimpleUser)authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();

        //只检查targetPermission....
        String permission=(String)targetPermission;  
        if(permission.indexOf(",")>0){
          String[] perms=	permission.split(",");
          for(String p: perms) {
        	boolean bl=  authorities.stream()
				  			.map(GrantedAuthority::getAuthority)
				  			.filter(StringUtils::hasText)
				  			.anyMatch(x -> PatternMatchUtils.simpleMatch(p, x));
        	if(bl) {
        		return true;
        	}
          }
          //--
          return false;
        }
        else {
	        return authorities.stream()
	    			.map(GrantedAuthority::getAuthority)
	    			.filter(StringUtils::hasText)
	    			.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
        }  
       
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}